<template>
  <div class="p-6px">
    <el-card class="rounded-md" shadow="never">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <!-- 基础信息 -->
        <el-tab-pane label="基础信息" name="first">
          <el-form ref="formRef" :rules="rules" :model="form" label-width="130px" status-icon>
            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="表名称" prop="tableName">
                  <el-input v-model="form.tableName" placeholder="请输入表名称" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="作者" prop="author">
                  <el-input v-model="form.author" placeholder="请输入作者名字" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="权限字符" prop="tableAuth">
                  <el-input v-model="form.tableAuth" placeholder="请输入权限字符" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="表描述" prop="tableComment">
                  <el-input v-model="form.tableComment" placeholder="请输入表描述" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="实体类" prop="className">
                  <el-input v-model="form.className" placeholder="请输入实体类名称" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="生成模版" prop="tableTemplate">
                  <el-select v-model="form.tableTemplate" placeholder="请选择模版类型" style="width: 260px" clearable>
                    <el-option label="CRUD模版" value="table" />
                    <el-option label="TREE模版" value="tree" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" class="p-l-10px">
                <el-form-item label="生成包路径" prop="packagePath">
                  <el-input v-model="form.packagePath" placeholder="请输入生成包路径" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row v-if="form.tableTemplate == 'tree'">
              <el-col :xs="{ span: 24 }" :sm="{ span: 8 }">
                <el-form-item label="树编码字段" prop="treeId">
                  <el-select v-model="form.treeId" placeholder="请选择树编码字段" style="width: 260px" clearable>
                    <el-option
                      v-for="item in columnOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 8 }" class="p-l-10px">
                <el-form-item label="树父编码字段" prop="treePid">
                  <el-select v-model="form.treePid" placeholder="请选择树编码字段" style="width: 260px" clearable>
                    <el-option
                      v-for="item in columnOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 8 }" class="p-l-10px">
                <el-form-item label="树编码名称" prop="treeName">
                  <el-select v-model="form.treeName" placeholder="请选择树编码名称" style="width: 260px" clearable>
                    <el-option
                      v-for="item in columnOptions"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="前端模块文件夹" prop="moduleFolder">
                  <el-input v-model="form.moduleFolder" placeholder="请输入前端模块文件夹名字" clearable />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" class="p-l-10px">
                <el-form-item label="前端页面文件夹" prop="pageFolder">
                  <el-input v-model="form.pageFolder" placeholder="请输入前端页面文件夹名字" clearable />
                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }">
                <el-form-item label="代码下载方式" prop="genType">
                  <el-radio-group v-model="form.genType">
                    <el-radio label="1" border >桌面下载</el-radio>
                    <el-radio label="2" border @click="handleCustomDownload">自定义路径</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" class="p-l-10px" v-if="form.genType == '2'">
                <el-form-item label="自定义路径" prop="genPath">
                  <el-input v-model="form.genPath" placeholder="请输入自定义路径" clearable />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          
          <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" class="mt-6px flex justify-center">
            <el-form-item>
              <el-button type="primary" plain @click="handleBasicConfigSave">保存</el-button>
              <el-button type="danger" plain @click="handleClose">关闭</el-button>
            </el-form-item>
          </el-col>
        </el-tab-pane>
        <!-- 字段配置 -->
        <el-tab-pane label="字段配置" name="second">
          <el-table v-loading="loading" border :data="tableList" :max-height="tableHeight" empty-text="暂时没有数据哟🌻">
            <el-table-column label="序号" prop="columnId" width="80px" align="center" type="index"></el-table-column>
            <el-table-column
              label="列名"
              prop="columnName"
              width="120px"
              align="center"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column label="字段描述" prop="columnName" width="180px" align="center" :show-overflow-tooltip="true">
              <template #default="scope">
                <el-input v-model="scope.row.columnComment"></el-input>
              </template>
            </el-table-column>
            <el-table-column
              label="列类型"
              prop="columnType"
              width="120px"
              align="center"
              :show-overflow-tooltip="true"
            ></el-table-column>
            <el-table-column label="JAVA类型" width="150px" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.javaType">
                  <el-option label="Long" value="Long" />
                  <el-option label="String" value="String" />
                  <el-option label="Date" value="Date" />
                  <el-option label="BigDecimal" value="BigDecimal" />
                  <el-option label="Integer" value="Integer" />
                  <el-option label="Boolean" value="Boolean" />
                  <el-option label="Double" value="Double" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="JAVA字段" width="150px" align="center">
              <template #default="scope">
                <el-input v-model="scope.row.javaField"></el-input>
              </template>
            </el-table-column>
            <el-table-column label="列表" width="80px" align="center">
              <template #default="scope">
                <el-checkbox true-label="0" false-label="1" v-model="scope.row.isList"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="搜索" width="80px" align="center">
              <template #default="scope">
                <el-checkbox true-label="0" false-label="1" v-model="scope.row.isSearch"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="查询方式" width="120px" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.searchType">
                  <el-option label="=" value="eq" />
                  <el-option label="LIKE" value="like" />
                  <el-option label=">" value="gt" />
                  <el-option label=">=" value="ge" />
                  <el-option label="<" value="lt" />
                  <el-option label="<=" value="le" />
                  <el-option label="!=" value="ne" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="表单" width="80px" align="center">
              <template #default="scope">
                <el-checkbox true-label="0" false-label="1" v-model="scope.row.isForm"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="是否校验" width="120px" align="center">
              <template #default="scope">
                <el-checkbox true-label="0" false-label="1" v-model="scope.row.isRule"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column label="显示类型" width="150px" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.elementType">
                  <el-option label="文本框" value="input" />
                  <el-option label="数字框" value="number" />
                  <el-option label="下拉框" value="select" />
                  <el-option label="单选框" value="radio" />
                  <el-option label="多选框" value="checkbox" />
                  <el-option label="日期控件" value="datetime" />
                  <el-option label="文本域" value="textarea" />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="字典类型" width="180px" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.dictType" clearable filterable placeholder="请选择字典类型">
                  <el-option v-for="dict in dictOptions" :key="dict.dictType" :label="dict.dictName" :value="dict.dictType">
                    <span style="float: left">{{ dict.dictName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ dict.dictType }}</span>
                  </el-option>
                </el-select>
              </template>
            </el-table-column>
          </el-table>
          <br/>
          <div class="flex justify-center">
              <el-button type="primary" plain @click="handleColumnConifgSave">保存</el-button>
              <el-button type="danger" plain @click="handleClose">关闭</el-button>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script setup lang="ts" name="configPage">
import { ref, reactive, onMounted } from "vue";
import { koiNoticeSuccess, koiNoticeError, koiMsgError, koiMsgWarning } from "@/utils/koi.ts";
import { getByTableName, update, listColumn, saveColumnData, listElSelectColumn } from "@/api/tools/gen/index.ts";
import { listDictType } from "@/api/system/dict/data/index.ts";
import { ElLoading } from 'element-plus';
import { useRoute, useRouter } from "vue-router";
import useTabsStore from "@/stores/modules/tabs.ts";

const route = useRoute();
const router = useRouter();
const tabsStore = useTabsStore();

const tableHeight = ref(document.documentElement.scrollHeight - 245 + "px");
const activeName = ref("first");

/** 获取点击选中的tab的name属性 */
const handleClick = (tab: any) => {
  if (tab.paneName == "first") {
    handleBasicInformation();
    handleColumnOptions();
  }
  if (tab.paneName == "second") {
    handleTableColumn();
  }
};

onMounted(() => {
  handleBasicInformation();
  handleColumnOptions();
});

// form表单Ref
const formRef = ref<any>();
// form表单
let form = ref<any>({
  tableName: "",
  tableComment: "",
  className: "",
  tableAuth: "",
  author: "",
  tableTemplate: "table",
  packagePath: "com.koi.system",
  treeId: "",
  treePid: "",
  treeName: "",
  moduleFolder: "",
  pageFolder: "",
  tableTitle: "",
  genType: "1",
  genPath: "C://Koi-Admin-GenCode"
});
/** 清空表单数据 */
const resetForm = () => {
  form.value = {
    tableName: "",
    tableComment: "",
    className: "",
    tableAuth: "",
    author: "",
    tableTemplate: "table",
    packagePath: "com.koi.system",
    treeId: "",
    treePid: "",
    treeName: "",
    moduleFolder: "",
    pageFolder: "",
    tableTitle: "",
    genType: "1",
    genPath: "C://Koi-Admin-GenCode"
  };
};
/** 表单规则 */
const rules = reactive({
  tableName: [{ required: true, message: "请输入表名称", trigger: "blur" }],
  tableComment: [{ required: true, message: "请输入表描述", trigger: "blur" }],
  className: [{ required: true, message: "请输入实体类名称", trigger: "blur" }],
  tableAuth: [{ required: true, message: "请输入权限字符", trigger: "blur" }],
  author: [{ required: true, message: "请输入作者名字", trigger: "blur" }],
  tableTemplate: [{ required: true, message: "请选择模版类型", trigger: "blur" }],
  packagePath: [{ required: true, message: "请输入生成包路径", trigger: "blur" }],
  moduleFolder: [{ required: true, message: "请输入前端模块文件夹名字", trigger: "blur" }],
  pageFolder: [{ required: true, message: "请输入前端页面文件夹名字", trigger: "blur" }],
  tableTitle: [{ required: true, message: "请输入前端模块文件夹名字", trigger: "blur" }]
});

/** 自定义路径 */
const handleCustomDownload = () => {
  form.value.genPath = "C://Koi-Admin-GenCode";
}

/** 保存 */
const handleBasicConfigSave = async () => {
  if (!formRef.value) return;
  const loading = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  });
  (formRef.value as any).validate(async (valid: any) => {
    if (valid) {
      const tableSchema = route.params.tableSchema;
      const tableName = route.params.tableName;
      if(form.value.genType == "1") {
        form.value.genPath = "local";
      }
      if(form.value.tableTemplate == 'table') {
        form.value.treeId = "";
        form.value.treePid = "";
        form.value.treeName = "";
      }
      if(form.value.tableTemplate == 'tree') {
        if(!form.value.treeId || !form.value.treePid || !form.value.treeName) {
          loading.close()
          koiMsgError("请选择树编码、树父编码、树编码名称🌻");
          return;
        }
      }
      if (tableSchema && tableName) {
        try {
          await update(form.value);
          loading.close()
          koiNoticeSuccess("保存成功🌻");
        } catch (error) {
          console.log(error);
          loading.close()
          koiNoticeError("修改失败，请刷新重试🌻");
        }
      } else {
        loading.close()
        koiNoticeError("修改失败，请刷新重试🌻");
      }
    } else {
      koiMsgError("验证失败，请检查填写内容🌻");
    }
  });
};

/** 关闭当前选项卡 */
const handleCloseCurrentTab = () => {
  if (route.meta?.isAffix == "0") return;
  tabsStore.removeTab(route.fullPath);
};

/** 返回 */
const handleClose = () => {
  handleCloseCurrentTab();
  router.push("/tools/gen");
};

/** 获取基本信息 */
const handleBasicInformation = async () => {
  const tableSchema = route.params.tableSchema;
  const tableName = route.params.tableName;
  if (!tableSchema || !tableName) {
    koiMsgWarning("未获取到表数据，请重试🌻");
  }
  resetForm();
  if (tableName) {
    try {
      const res: any = await getByTableName(tableSchema, tableName);
      form.value = res.data;
      form.value.genType = "1";
      koiNoticeSuccess("获取基本信息成功🌻");
    } catch (error) {
      console.log(error);
      koiNoticeError("获取基本信息失败，请刷新重试🌻");
    }
  }
};

/** 当前表列名下拉框 */
const columnOptions = ref();
const handleColumnOptions = async () => {
  const tableSchema = route.params.tableSchema;
  const tableName = route.params.tableName;
  if (!tableSchema || !tableName) {
    koiMsgWarning("未获取到表数据，请重试🌻");
  }
  try {
    const res: any = await listElSelectColumn(tableSchema, tableName);
    columnOptions.value = res.data;
  } catch (error) {
    console.log(error);
    koiNoticeError("获取表列名下拉框失败，请刷新重试🌻");
  }
}

/** 字段配置 */
const loading = ref(false);
const tableList = ref();

/** 查询字段配置 */
const handleTableColumn = async () => {
  handleDictType();
  loading.value = true;
  const tableSchema = route.params.tableSchema;
  const tableName = route.params.tableName;
  if (!tableSchema || !tableName) {
    koiMsgWarning("未获取到表数据，请重试🌻");
  }
  try {
    const res: any = await listColumn(tableSchema, tableName);
    tableList.value = res.data;
    loading.value = false;
    koiNoticeSuccess("获取列字段配置成功🌻");
  } catch (error) {
    console.log(error);
    loading.value = false;
    koiNoticeError("获取列字段配置失败，请刷新重试🌻");
  }
};

/** 字典类型 */
// 字典类型名称下拉框
const dictOptions = ref();
/** 字典类型名称下拉框 */
const handleDictType = async () => {
  try {
    const res: any = await listDictType();
    dictOptions.value = res.data;
  } catch (error) {
    console.log(error);
    koiNoticeError("获取字典类型失败，请刷新重试🌻");
  }
};

/** 列配置保存 */
const handleColumnConifgSave = async () => {
  loading.value = true;
  try {
    await saveColumnData(tableList.value);
    loading.value = false;
    koiNoticeSuccess("保存成功🌻");
  } catch (error) {
    console.log(error);
    loading.value = false;
    koiNoticeError("保存失败🌻");
  }
}
</script>

<style lang="scss" scoped></style>
